import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import {Table, Button, Input, Space, Checkbox,Card, Typography, Popconfirm, Tooltip,notification, Tag, Pagination} from 'antd';
import { DeleteOutlined, EditOutlined,CheckOutlined, CloseOutlined, ArrowRightOutlined} from '@ant-design/icons';

import type { TodoPreview, AddTodoType, UpdateTodoType } from '../services/todo';
import {
  fetchTodes, addTodo, deleteTodo, updateTodo
} from '../services/todo';

const { Title, Text } = Typography;
const { Search } = Input;

const TodoListPage: React.FC = () => {
  const [todos, setTodos] = useState<TodoPreview[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [newTitle, setNewTitle] = useState<string>('');
  const [editId, setEditId] = useState<number | null>(null);
  const [selected, setSelected] = useState<Record<number, boolean>>({});
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(2);
  const navigate = useNavigate();

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    setLoading(true);
    try {
      const res = await fetchTodes();
      setTodos(res.slice(0, 10));
    } catch (error) {
      notification.error({
        message: '加载失败',
        description: '无法获取待办事项数据',
      });
    } finally {
      setLoading(false);
    }
  };

  const handleAdd = async () => {
    if (newTitle.trim().length === 0) {
      notification.warning({
        message: '标题不能为空',
        description: '请输入待办事项标题',
      });
      return;
    }

    const newTodo: AddTodoType = {
      userId: 1,
      title: newTitle,
      completed: false,
    };

    try {
      const res = await addTodo(newTodo);
      setTodos([res, ...todos]);
      setNewTitle('');
      notification.success({
        message: '添加成功',
        description: '已成功添加新的待办事项',
      });
    } catch (error) {
      notification.error({
        message: '添加失败',
        description: '无法添加新的待办事项',
      });
    }
  };

  const handleDelete = async (id: number) => {
    try {
      await deleteTodo(id);
      setTodos(todos.filter((todo) => todo.id !== id));
      setSelected((prev) => {
        const newSelected = { ...prev };
        delete newSelected[id];
        return newSelected;
      });
      notification.success({
        message: '删除成功',
        description: '待办事项已成功删除',
      });
    } catch (error) {
      notification.error({
        message: '删除失败',
        description: '无法删除待办事项',
      });
    }
  };

  const handleEdit = async (id: number) => {
    if (newTitle.trim().length === 0) {
      notification.warning({
        message: '标题不能为空',
        description: '请输入待办事项标题',
      });
      return;
    }

    const editTodo: UpdateTodoType = {
      title: newTitle,
    };

    try {
      await updateTodo(id, editTodo);
      setTodos(
        todos.map((todo) =>
          todo.id === id ? { ...todo, title: newTitle } : todo
        )
      );
      setEditId(null);
      setNewTitle('');
      notification.success({
        message: '更新成功',
        description: '待办事项已成功更新',
      });
    } catch (error) {
      notification.error({
        message: '更新失败',
        description: '无法更新待办事项',
      });
    }
  };

  const handleBatchDelete = async () => {
    const deleteIds = Object.entries(selected)
      .filter(([_, value]) => value)
      .map(([key]) => parseInt(key));

    if (deleteIds.length === 0) {
      notification.warning({
        message: '未选择项目',
        description: '请选择要删除的待办事项',
      });
      return;
    }

    try {
      await Promise.all(deleteIds.map((id) => deleteTodo(id)));
      setTodos(todos.filter((t) => !deleteIds.includes(t.id)));
      setSelected({});
      notification.success({
        message: '批量删除成功',
        description: `已成功删除 ${deleteIds.length} 个待办事项`,
      });
    } catch (error) {
      notification.error({
        message: '删除失败',
        description: '无法删除选中的待办事项',
      });
    }
  };

  const toggleTodo = (id: number) => {
    setSelected((prev) => ({ ...prev, [id]: !prev[id] }));
  };

  const toggleSelectAll = () => {
    if (todos.length > 0 && todos.every((t) => selected[t.id])) {
      setSelected({});
    } else {
      const newSelected: Record<number, boolean> = {};
      todos.forEach((todo) => {
        newSelected[todo.id] = true;
      });
      setSelected(newSelected);
    }
  };

  const handleViewDetail = (id: number) => {
    navigate(`/todo/${id}`);
  };

  const columns = [
    {
      title: (
        <Checkbox
          checked={todos.length > 0 && todos.every((t) => selected[t.id])}
          onChange={toggleSelectAll}
        />
      ),
      dataIndex: 'id',
      key: 'selection',
      width: 60,
      render: (_: any, record: TodoPreview) => (
        <Checkbox
          checked={!!selected[record.id]}
          onChange={() => toggleTodo(record.id)}
        />
      ),
    },
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
      sorter: (a: TodoPreview, b: TodoPreview) => a.id - b.id,
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      render: (text: string, record: TodoPreview) => {
        if (editId === record.id) {
          return (
            <Input
              value={newTitle}
              onChange={(e) => setNewTitle(e.target.value)}
              onPressEnter={() => handleEdit(record.id)}
              autoFocus
            />
          );
        }
        return (
          <div onClick={() => handleViewDetail(record.id)} style={{ cursor: 'pointer' }}>
            {record.completed ? <s>{text}</s> : <span>{text}</span>}
          </div>
        );
      },
    },
    {
      title: '状态',
      dataIndex: 'completed',
      key: 'completed',
      width: 100,
      render: (completed: boolean) => (
        <Tag color={completed ? 'success' : 'warning'}>
          {completed ? <CheckOutlined /> : <CloseOutlined />}
          {completed ? ' 已完成' : ' 未完成'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_: any, record: TodoPreview) => {
        if (editId === record.id) {
          return (
            <Space>
              <Button type="primary" size="small" onClick={() => handleEdit(record.id)}>
                保存
              </Button>
              <Button
                size="small"
                onClick={() => {
                  setEditId(null);
                  setNewTitle('');
                }}
              >
                取消
              </Button>
            </Space>
          );
        }
        return (
          <Space>
            <Tooltip title="编辑">
              <Button
                type="primary"
                icon={<EditOutlined />}
                size="small"
                onClick={(e) => {
                  e.stopPropagation();
                  setEditId(record.id);
                  setNewTitle(record.title);
                }}
              />
            </Tooltip>
            <Tooltip title="删除">
              <Popconfirm
                title="确定要删除吗？"
                onConfirm={(e) => {
                  e?.stopPropagation();
                  handleDelete(record.id);
                }}
                okText="确定"
                cancelText="取消"
              >
                <Button
                  type="primary"
                  danger
                  icon={<DeleteOutlined />}
                  size="small"
                  onClick={(e) => e.stopPropagation()}
                />
              </Popconfirm>
            </Tooltip>
            <Tooltip title="查看详情">
              <Button
                type="default"
                icon={<ArrowRightOutlined />}
                size="small"
                onClick={(e) => {
                  e.stopPropagation();
                  handleViewDetail(record.id);
                }}
              />
            </Tooltip>
          </Space>
        );
      },
    },
  ];

  const selectedCount = Object.values(selected).filter(Boolean).length;

  // 分页处理
  const startIndex = (currentPage - 1) * pageSize;
  const paginatedTodos = todos.slice(startIndex, startIndex + pageSize);

  return (
    <div>
      <Title level={3} style={{ marginBottom: 24 }}>待办事项管理</Title>

      <Card style={{ marginBottom: 24 }} className="action-bar">
        <Space style={{ width: '100%' }} direction="vertical">
          <Space>
            <Search
              placeholder="请输入待办事项标题"
              enterButton="添加"
              value={newTitle}
              onChange={(e) => setNewTitle(e.target.value)}
              onSearch={handleAdd}
              style={{ width: 400 }}
            />
            <Button
              type="primary"
              danger
              icon={<DeleteOutlined />}
              onClick={handleBatchDelete}
              disabled={selectedCount === 0}
            >
              批量删除 ({selectedCount})
            </Button>
          </Space>

          <Text type="secondary">
            共 {todos.length} 个待办事项，已完成 {todos.filter(t => t.completed).length} 个
          </Text>
        </Space>
      </Card>

      <Table
        columns={columns}
        dataSource={paginatedTodos}
        rowKey="id"
        loading={loading}
        pagination={false}
        rowClassName={(record) =>
          selected[record.id] ? 'selected-row' : ''
        }
      />

      <Pagination
        current={currentPage}
        pageSize={pageSize}
        total={todos.length}
        align="end"
        showSizeChanger
        pageSizeOptions={['2', '5', '10']}
        onChange={(page, size) => {
          setCurrentPage(page);
          setPageSize(size);
        }}
        style={{ marginTop: 24, textAlign: 'right' }}
      />
    </div>
  );
};

export default TodoListPage;